import request from '@/utils/request'
import Cookies from "js-cookie";
export default {
  data() {
    return {
      tableData: [],
      loading: false,
      query: {
        size: 10,
        current: 1,
        input: {}
      },
      editVisible: false,
      multipleSelection: [],
      total: 0,
      tagList: [],
      type: 'add',
      userInfo: {}
    }
  },
  created(){
    this.userInfo = JSON.parse(Cookies.get("userInfo"));
    this.queryList()
  },
  methods: {
    // 列表查询
    queryList() {
      this.loading = true
      request({
        url: this.queryUrl,
        method: this.querymethod || 'post',
        data: this.query
      }).then(res => {
        this.tableData = (this.querymethod && this.querymethod== 'get') ? res.data || []: (res.data.records || [])
        this.total = parseInt(res.data.total)
      }).finally(() => {
        this.loading = false
      })
    },
    // 分页切换
    currentChange(val){
      this.query.current = val
      this.queryList()
    },
    // 打开详情
    handleDetail(row){
      this.type = 'detail'
      this.dialogFrom = row
      this.editVisible = true
    },
    // 打开编辑
    handleEdit(row){
      this.type = 'edit'
      this.dialogFrom = row
      this.editVisible = true
    },
    // 编辑确定
    handleUpdate(formName){
      this.loading = true
      request({
        url: this.editUrl,
        method: this.updatemethod || 'put',
        data: this[formName]
      }).then(res => {
        this.$message.success(res.msg || '操作成功')
        this.editVisible = false
        this.resetTable()
      })
    },
    toAdd(form = {}){
      this.type = 'add'
      this.dialogFrom = form
      this.editVisible = true
    },
    // 新增
    handleAdd(formName){
      this.loading = true
      request({
        url: this.addUrl,
        method: this.addmethod || 'post',
        data: this[formName]
      }).then(res => {
        this.$message.success(res.msg || '操作成功')
        this.editVisible = false
        this.resetTable()
      })
    },
    // 删除
    handleDelete(row){
      this.delete(row.id)
    },
    resetTable(){
      this.tableData = []
      this.query = {
        size: 10,
        current: 1,
        input: {}
      }
      this.queryList()
    },
    delete(data){
      this.loading = true
      request({
        url: this.delUrl+'/' + data,
        method: this.method || 'delete'
      }).then(res => {
        this.$message.success(res.msg || '删除成功')
        this.resetTable()
      })
    },
    handleSelectionChange(val){
      this.multipleSelection = val
    },
    handleSure(formName='dialogFrom'){
      if(this.type == 'add'){
        this.handleAdd(formName)
      }else{
        this.handleUpdate(formName)
      }
    },
    getAllTag(){
      request({
        url: '/tag/all',
        method: 'get',
      }).then(res => {
        this.tagList = res.data
      })
    },
  },
}
